package com.work.studio.views;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.work.studio.R;
import com.work.studio.entitys.AttendanceStatisticsEntity;
import com.work.studio.entitys.CustomerVisitRntity;
import com.work.studio.entitys.DailyFinishEntity;
import com.work.studio.entitys.RankingEntity;
import com.work.studio.recy.CommonAdapter;
import com.work.studio.recy.base.ViewHolder;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class DataStatisticsViews extends FrameLayout implements OnChartValueSelectedListener {


    //今日考勤
    //根布局
    private View viewStatisticsToday = null;
    //出差
    private TextView businessTravelValue;
    //内勤
    private TextView officeWorkValue;
    //缺勤
    private TextView absenceWorkValue;
    //饼状图
    private PieChart viewStatisticsTodayPieChart;
    //昨日日报完成率
    private PieChart leftPieChart;
    private PieChart rightPieChart;
    //客户拜访次数日统计
    private BarChart barChart;
    private Context mContext;
    //7月客户拜访排行榜
    private TextView titleValue;
    private RecyclerView recycleView;
    private CommonAdapter<RankingEntity> adapter;
    private List<RankingEntity> datas = new LinkedList<>();
//    private int maxValue = 100;//进度条最大值

    public DataStatisticsViews(Context context) {
        this(context, null);
    }

    public DataStatisticsViews(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DataStatisticsViews(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);


        LayoutInflater inflater = LayoutInflater.from(context);

        this.mContext = context;
        View view = inflater.inflate(R.layout.view_left_content, null);

        addView(view);

        viewStatisticsToday = view.findViewById(R.id.view_statistics_today);
        businessTravelValue = view.findViewById(R.id.business_travel_value);
        officeWorkValue = view.findViewById(R.id.office_work_value);
        absenceWorkValue = view.findViewById(R.id.absence_work_value);
        viewStatisticsTodayPieChart = view.findViewById(R.id.view_statistics_today_pie_chart);

        leftPieChart = view.findViewById(R.id.left_pie_chart);
        rightPieChart = view.findViewById(R.id.right_pie_chart);

        barChart = view.findViewById(R.id.bar_chart);

        recycleView = view.findViewById(R.id.recycle_view);
        titleValue = view.findViewById(R.id.title_value);

        initPieToday();
//        setPieToday(null);


        initLeftPieChart();
//        setLeftPieChart(null);

        initRightPieChart();
//        setRightPieChart(null);


        initBarChart();
        setBarChart(null);


        initRanking();
    }

    /**
     * 初始化
     */
    private void initPieToday() {
        try {

            viewStatisticsTodayPieChart.setUsePercentValues(true);
            viewStatisticsTodayPieChart.getDescription().setEnabled(false);

            viewStatisticsTodayPieChart.setDragDecelerationFrictionCoef(0.95f);

//            tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");

//            viewStatisticsTodayPieChart.setCenterTextTypeface(Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf"));
//            viewStatisticsTodayPieChart.setCenterText(generateCenterSpannableText());

            viewStatisticsTodayPieChart.setExtraOffsets(13, 13, 13, 0);

            viewStatisticsTodayPieChart.setDrawHoleEnabled(true);
            viewStatisticsTodayPieChart.setHoleColor(Color.TRANSPARENT);

            viewStatisticsTodayPieChart.setTransparentCircleColor(Color.WHITE);
//            viewStatisticsTodayPieChart.setTransparentCircleAlpha(50);
            viewStatisticsTodayPieChart.setHoleRadius(50f);
//            viewStatisticsTodayPieChart.setTransparentCircleRadius(53f);

            viewStatisticsTodayPieChart.setDrawCenterText(false);

            viewStatisticsTodayPieChart.setRotationAngle(0);
            // enable rotation of the chart by touch
            viewStatisticsTodayPieChart.setRotationEnabled(true);
            viewStatisticsTodayPieChart.setHighlightPerTapEnabled(true);

            // chart.setUnit(" €");
            // chart.setDrawUnitsInChart(true);

            // add a selection listener
            viewStatisticsTodayPieChart.setOnChartValueSelectedListener(this);

//            seekBarX.setProgress(4);
//            seekBarY.setProgress(100);
//
            viewStatisticsTodayPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
            // chart.spin(2000, 0, 360);



            viewStatisticsTodayPieChart.setDrawEntryLabels(true);              //设置pieChart是否只显示饼图上百分比不显示文字（true：下面属性才有效果）
            viewStatisticsTodayPieChart.setEntryLabelColor(Color.WHITE);       //设置pieChart图表文本字体颜色
            viewStatisticsTodayPieChart.setEntryLabelTextSize(8f);


            Legend l = viewStatisticsTodayPieChart.getLegend();
            l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
            l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
            l.setOrientation(Legend.LegendOrientation.VERTICAL);
            l.setDrawInside(false);
            l.setEnabled(false);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *初始化
     * @param today
     */
    public void setPieToday(AttendanceStatisticsEntity today) {

        try {

            ArrayList<PieEntry> entries = new ArrayList<>();


            List<String> title = new LinkedList<>();
            List<Integer> integers = new LinkedList<>();

            int bussiness_in_trip_count = today.getBussiness_in_trip_count();
            int internal_count = today.getInternal_count();
            int no_sign_user = today.getNo_sign_user();
            if (bussiness_in_trip_count > 0) {
                title.add("出差");
                integers.add(bussiness_in_trip_count);
            }
            if (internal_count > 0) {
                title.add("内勤");
                integers.add(internal_count);
            }
            if (no_sign_user > 0) {
                title.add("缺勤");
                integers.add(no_sign_user);
            }

            businessTravelValue.setText(""+bussiness_in_trip_count+"人");
            officeWorkValue.setText(""+internal_count+"人");
            absenceWorkValue.setText(""+no_sign_user+"人");

            for (int i = 0; i < integers.size(); i++) {
                entries.add(new PieEntry(integers.get(i), title.get(i)));
            }

            PieDataSet dataSet = new PieDataSet(entries, "Election Results");
            dataSet.setDrawValues(true);
            dataSet.setSliceSpace(0f);//设置饼状Item之间的间隙
            dataSet.setSelectionShift(0f); //设置饼状Item被选中时变化的距离
            dataSet.setValueTextSize(80);
            dataSet.setValueTextColor(Color.RED);
            dataSet.setValueLineColor(Color.WHITE);
            // add a lot of colors

            ArrayList<Integer> colors = new ArrayList<>();

            colors.add(Color.rgb(220,20,60));
            colors.add(Color.rgb(	0,0,255));
            colors.add(Color.rgb(255,215,0));

            colors.add(Color.rgb(220,20,60));

            dataSet.setColors(colors);

            dataSet.setValueLinePart1OffsetPercentage(80.f);
            dataSet.setValueLinePart1Length(0.2f);
            dataSet.setValueLinePart2Length(0.4f);

            //dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
            dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

            PieData data = new PieData(dataSet);
            data.setValueFormatter(new PercentFormatter());
            data.setValueTextSize(9f);
            data.setValueTextColor(Color.WHITE);
//            data.setValueTypeface(tf);
            viewStatisticsTodayPieChart.setData(data);

            // undo all highlights
            viewStatisticsTodayPieChart.highlightValues(null);

            viewStatisticsTodayPieChart.invalidate();

            viewStatisticsTodayPieChart.animateXY(1400, 1400);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * PieToday -- onValueSelected
     * @param e
     * @param h
     */
    @Override
    public void onValueSelected(Entry e, Highlight h) {
        if (e == null)
            return;
        Log.e("VAL SELECTED",
                "Value: " + e.getY() + ", xIndex: " + e.getX()
                        + ", DataSet index: " + h.getDataSetIndex());
    }

    /**
     * PieToday -- onNothingSelected
     */
    @Override
    public void onNothingSelected() {

    }


    /**
     * 初始化
     */
    private void initLeftPieChart() {

        try {

            leftPieChart.setUsePercentValues(true);
            leftPieChart.getDescription().setEnabled(false);
            leftPieChart.setExtraOffsets(0, 0, 0, 0);


            leftPieChart.setDrawHoleEnabled(false);
            leftPieChart.setHoleColor(Color.WHITE);

//            leftPieChart.setTransparentCircleColor(Color.WHITE);
//            leftPieChart.setTransparentCircleAlpha(110);
//
//            leftPieChart.setHoleRadius(58f);
//            leftPieChart.setTransparentCircleRadius(61f);

            leftPieChart.setDrawCenterText(false);

            leftPieChart.setRotationAngle(0);
            // enable rotation of the chart by touch
            leftPieChart.setRotationEnabled(true);
            leftPieChart.setHighlightPerTapEnabled(true);

            // chart.setUnit(" €");
            // chart.setDrawUnitsInChart(true);

            // add a selection listener
            leftPieChart.setOnChartValueSelectedListener(this);
            leftPieChart.setDrawEntryLabels(false);

            leftPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
            // chart.spin(2000, 0, 360);

            Legend l = leftPieChart.getLegend();
            l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
            l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
            l.setOrientation(Legend.LegendOrientation.VERTICAL);
            l.setDrawInside(false);
            l.setEnabled(false);



            // entry label styling
            leftPieChart.setDrawEntryLabels(true);
            leftPieChart.setEntryLabelColor(Color.WHITE);
            leftPieChart.setEntryLabelTextSize(7f);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void setLeftPieChart(ArrayList<PieEntry> entries) {

        try {

            PieDataSet dataSet = new PieDataSet(entries, "Election Results");

            dataSet.setDrawIcons(false);
            dataSet.setSliceSpace(0f);
            dataSet.setDrawValues(true);
//            dataSet.setIconsOffset(new MPPointF(0, 40));
            dataSet.setSelectionShift(5f);

            // add a lot of colors

            ArrayList<Integer> colors = new ArrayList<>();
            colors.add(Color.rgb(13, 22, 93));
            colors.add(Color.rgb(80,166,252));

            colors.add(Color.rgb(13, 22, 93));

            dataSet.setColors(colors);
            //dataSet.setSelectionShift(0f);

            PieData data = new PieData(dataSet);
            data.setValueFormatter(new PercentFormatter());
            data.setValueTextSize(8f);
            data.setValueTextColor(Color.WHITE);
            leftPieChart.setData(data);

            // undo all highlights
            leftPieChart.highlightValues(null);

            leftPieChart.invalidate();
            leftPieChart.animateXY(1400, 1400);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化
     */
    private void initRightPieChart() {

        try {

            rightPieChart.setUsePercentValues(true);
            rightPieChart.getDescription().setEnabled(false);
            rightPieChart.setExtraOffsets(0, 0, 0, 0);

            rightPieChart.setDragDecelerationFrictionCoef(0.95f);



            rightPieChart.setDrawHoleEnabled(false);
            rightPieChart.setHoleColor(Color.WHITE);

//            leftPieChart.setTransparentCircleColor(Color.WHITE);
//            leftPieChart.setTransparentCircleAlpha(110);
//
//            leftPieChart.setHoleRadius(58f);
//            leftPieChart.setTransparentCircleRadius(61f);

            rightPieChart.setDrawCenterText(false);

            rightPieChart.setRotationAngle(0);
            // enable rotation of the chart by touch
            rightPieChart.setRotationEnabled(true);
            rightPieChart.setHighlightPerTapEnabled(true);

            // chart.setUnit(" €");
            // chart.setDrawUnitsInChart(true);

            // add a selection listener
            rightPieChart.setOnChartValueSelectedListener(this);
            rightPieChart.setDrawEntryLabels(false);

            rightPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
            // chart.spin(2000, 0, 360);

            Legend l = rightPieChart.getLegend();
            l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
            l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
            l.setOrientation(Legend.LegendOrientation.VERTICAL);
            l.setDrawInside(false);
            l.setEnabled(false);



            // entry label styling
            rightPieChart.setDrawEntryLabels(true);
            rightPieChart.setEntryLabelColor(Color.WHITE);
            rightPieChart.setEntryLabelTextSize(7f);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void setRightPieChart(ArrayList<PieEntry> entries) {

        try {


            PieDataSet dataSet = new PieDataSet(entries, "Election Results");

            dataSet.setDrawIcons(false);
            dataSet.setSliceSpace(0f);
            dataSet.setDrawValues(true);
//            dataSet.setIconsOffset(new MPPointF(0, 40));
            dataSet.setSelectionShift(5f);

            // add a lot of colors

            ArrayList<Integer> colors = new ArrayList<>();

            colors.add(Color.rgb(13,22,93));
            colors.add(Color.rgb(34,211,127));


            colors.add(Color.rgb(13, 22, 93));

            dataSet.setColors(colors);
            //dataSet.setSelectionShift(0f);

            PieData data = new PieData(dataSet);
            data.setValueFormatter(new PercentFormatter());
            data.setValueTextSize(8f);
            data.setValueTextColor(Color.WHITE);
            rightPieChart.setData(data);

            // undo all highlights
            rightPieChart.highlightValues(null);

            rightPieChart.invalidate();
            rightPieChart.animateXY(1400, 1400);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Left And Right datas
     * @param content
     */
    public void setPieChartDatas(DailyFinishEntity content) {


        try {

            if (content == null) {
                return;
            }

            int count1 = content.getCount1();
            int count2 = content.getCount2();
            int dept1_count = content.getDept1_count();
            int dept2_count = content.getDept2_count();


            ArrayList<PieEntry> entriesCount1 = new ArrayList<>();
            String[] ri = {"完成率", "未完成"};
            int [] valuesCount1 = {count1, dept1_count-count1};
            for (int i = 0; i < valuesCount1.length ; i++) {
                PieEntry pieEntry = new PieEntry(valuesCount1[i],ri [i]);
                entriesCount1.add(pieEntry);
            }

            ArrayList<PieEntry> entriesCount2 = new ArrayList<>();
            int [] valuesCount2 = {count2, dept2_count-count2};
            for (int i = 0; i < valuesCount1.length ; i++) {
                PieEntry pieEntry = new PieEntry(valuesCount2[i],ri [i]);
                entriesCount2.add(pieEntry);
            }
            setLeftPieChart(entriesCount1);
            setRightPieChart(entriesCount2);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化
     */
    private void initBarChart() {

        try {

            barChart.setOnChartValueSelectedListener(this);

            barChart.setDrawBarShadow(false);
            barChart.setDrawValueAboveBar(true);

            barChart.getDescription().setEnabled(false);

            // if more than 60 entries are displayed in the chart, no values will be
            // drawn
            barChart.setMaxVisibleValueCount(60);

            // scaling can now only be done on x- and y-axis separately
            barChart.setPinchZoom(false);

            barChart.setDrawGridBackground(false);
            // chart.setDrawYLabels(false);

//            IAxisValueFormatter xAxisFormatter = new DayAxisValueFormatter(chart);

            XAxis xAxis = barChart.getXAxis();
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setTextColor(Color.WHITE);
//            xAxis.setTypeface(tfLight);
            xAxis.setDrawGridLines(false);
            xAxis.setGranularity(1f); // only intervals of 1 day
            xAxis.setLabelCount(7);
//            xAxis.setValueFormatter(xAxisFormatter);

//            IAxisValueFormatter custom = new MyAxisValueFormatter();

            YAxis leftAxis = barChart.getAxisLeft();
//            leftAxis.setTypeface(tfLight);
            leftAxis.setLabelCount(8, false);
            leftAxis.setTextColor(Color.WHITE);
//            leftAxis.setValueFormatter(custom);
            leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
            leftAxis.setSpaceTop(15f);
            leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

            YAxis rightAxis = barChart.getAxisRight();
            rightAxis.setDrawZeroLine(false);
            rightAxis.setDrawLabels(false);
            rightAxis.setDrawGridLines(false);

//            rightAxis.setTypeface(tfLight);
            rightAxis.setLabelCount(8, false);
//            rightAxis.setTextColor(Color.WHITE);
//            rightAxis.setValueFormatter(custom);
            rightAxis.setSpaceTop(15f);
            rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

            Legend l = barChart.getLegend();
            l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
            l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
            l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
            l.setDrawInside(false);
            l.setEnabled(false);
            l.setForm(Legend.LegendForm.SQUARE);
            l.setFormSize(9f);
            l.setTextSize(11f);
            l.setXEntrySpace(4f);

//            XYMarkerView mv = new XYMarkerView(this, xAxisFormatter);
//            mv.setChartView(chart); // For bounds control
//            chart.setMarker(mv); // Set the marker to the chart

            setBarChart(null);



        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void setBarChart(List<CustomerVisitRntity> customerVisitRntities) {

        try {

            if (customerVisitRntities == null || customerVisitRntities.size() <=0 ) {
                return;
            }

            ArrayList<BarEntry> values = new ArrayList<>();

            for (int i = 0 ; i < customerVisitRntities.size() ; i++) {

                values.add(new BarEntry(i+1, customerVisitRntities.get(i).getCount()));

            }

            BarDataSet set1;
            set1 = new BarDataSet(values, "The year 2021");

            set1.setDrawIcons(false);
            set1.setBarBorderColor(Color.WHITE);

            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setValueTextColor(Color.WHITE);
//                data.setValueTypeface(tfLight);
            data.setBarWidth(0.9f);
            barChart.setData(data);
            barChart.postInvalidate();

            barChart.animateXY(2000, 2000);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private int maxProgress = 100;
    /**
     * 初始化
     */
    private void initRanking() {

        try {


            adapter = new CommonAdapter<RankingEntity>(mContext, R.layout.item_ranking, datas) {
                @Override
                protected void convert(ViewHolder holder, RankingEntity item, int position) {

                    if (position == 0) {
                        int count = item.getCount();
                        if (count > 100) {
                            maxProgress += 20;
                        } else {
                            maxProgress = 100;
                        }
                    }

                    holder.setText(R.id.no_value, ""+(position+1));
                    holder.setText(R.id.name_value, ""+item.getUserName());
                    holder.setText(R.id.count_value, ""+item.getCount());
                    ProgressBar progressBar = holder.getView(R.id.hori_progress);
                    progressBar.setMax(maxProgress);
                    progressBar.setProgress(item.getCount());

                }
            };

            recycleView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
            LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(mContext, R.anim.layout_animation_fall_down);
            recycleView.setLayoutAnimation(animation);
            recycleView.setAdapter(adapter);


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void setRanking(List<RankingEntity> rankingEntities) {

        datas.clear();
        if (rankingEntities != null && rankingEntities.size() > 0) {
            datas.addAll(rankingEntities);
        }

        if (adapter != null) {
            Context context = recycleView.getContext();
            LayoutAnimationController controller =
                    AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down);
            recycleView.setLayoutAnimation(controller);
            recycleView.getAdapter().notifyDataSetChanged();
            recycleView.scheduleLayoutAnimation();
        }
    }
}
